package com.glwan.fixedassetapp.ui.home.Activity;

import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;

import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;

import com.glwan.fixedassetapp.Adapter.MapAdapter;
import com.glwan.fixedassetapp.R;
import com.glwan.fixedassetapp.utils.CommonUtil;
import com.glwan.fixedassetapp.utils.KingDeeCommonUtil;
import com.glwan.fixedassetapp.utils.KingDeeUtil;

import org.apache.commons.lang.StringUtils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class AddAssetActivity extends AppCompatActivity {

    private ExecutorService executorService = Executors.newSingleThreadExecutor();
    Handler handler = new Handler(Looper.getMainLooper());

    private EditText fAssetNo;
    private EditText fAssetName;
    private EditText fQuantity;
    private Spinner fAssetUnitID;
    private String fAssetUnitIDNumber;
    private Button submitAsset;

    private Spinner fAssetType;
    private String fAssetTypeNumber;
    private Spinner fAssetStatus;
    private String fAssetStatusNumber;
    private Spinner fAssetPosition;
    private String fAssetPositionNumber;

    private EditText fAcctDate;
    private EditText fOrginalCost;
    private Spinner fAcctPolicy;
    private String fAcctPolicyNumber;
    private Spinner fAllocUseDept;
    private String fAllocUseDeptNumber;
    private Spinner fAllocCostItem;
    private String fAllocCostItemNumber;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.add_asset);

        Toolbar toolbar = findViewById(R.id.moreToolbar);
        setSupportActionBar(toolbar);
        setTitle(getString(R.string.addAsset));
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.setHomeButtonEnabled(true);
            actionBar.setDisplayHomeAsUpEnabled(true);
        }

        // 通过 ID 绑定布局中的视图组件
        fAssetNo = findViewById(R.id.fAssetNo);
        fAssetName = findViewById(R.id.fAssetName);
//        fQuantity = findViewById(R.id.fQuantity);
        fAssetUnitID = findViewById(R.id.fAssetUnitID);
        fAssetType = findViewById(R.id.fAssetType);
        fAssetStatus = findViewById(R.id.fAssetStatus);
        fAssetPosition = findViewById(R.id.fAssetPosition);
        //会计政策
        fAcctDate = findViewById(R.id.fAcctDate);
        fOrginalCost = findViewById(R.id.fOriginalCost);
        fAcctPolicy = findViewById(R.id.fAcctPolicy);
        //使用分配
        fAllocUseDept = findViewById(R.id.fAllocUseDept);
        fAllocCostItem = findViewById(R.id.fAllocCostItem);

        initData();


        submitAsset = findViewById(R.id.submitAsset);
        // 设置按钮点击事件监听器
        submitAsset.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 获取用户输入的数据
                String assetNo = fAssetNo.getText().toString().trim();
                String assetName = fAssetName.getText().toString().trim();
//                String quantity = fQuantity.getText().toString().trim();
                String quantity = "1";
                String orginalCost = fOrginalCost.getText().toString().trim();
                String acctDate = fAcctDate.getText().toString().trim();
                String unit = fAssetUnitIDNumber;
                String position = fAssetPositionNumber;
                String type = fAssetTypeNumber;
                String policy = fAcctPolicyNumber;
                String useDept = fAllocUseDeptNumber;
                String allocCostItem = fAllocCostItemNumber;
                String status = fAssetStatusNumber;


                // 检查是否有必要的数据未输入
                if (assetNo.isEmpty() || assetName.isEmpty() || quantity.isEmpty()
                        || orginalCost.isEmpty() || acctDate.isEmpty() || unit.isEmpty()
                        || position.isEmpty() || type.isEmpty() || policy.isEmpty()
                        || useDept.isEmpty() || allocCostItem.isEmpty() || status.isEmpty()) {
                    CommonUtil.toastShow(AddAssetActivity.this, "请填写所有必要信息", 1, false);
                } else {
                    //判断日期格式
                    String DATE_FORMAT = "yyyy-MM-dd";
                    SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT);
                    try {
                        sdf.parse(acctDate);
                        submitAssetData(assetNo, assetName, quantity, unit, position, type, policy, orginalCost, acctDate, useDept, allocCostItem, status);
                    } catch (ParseException e) {
                        CommonUtil.toastShow(AddAssetActivity.this, "入账日期格式错误，yyyy-MM-dd", 1, false);
                    }
                }
            }
        });


    }

    private void initUnitData() {
        Map<String, String> unitMap = KingDeeCommonUtil.getAssetUnit();
        MapAdapter unitAdapter = new MapAdapter(this, unitMap);
        handler.post(new Runnable() {
            @Override
            public void run() {
                fAssetUnitID.setAdapter(unitAdapter);

                // 设置 Spinner 的选项选择监听器
                fAssetUnitID.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                    @Override
                    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                        Map.Entry<String, String> selectedItem = (Map.Entry<String, String>) parent.getItemAtPosition(position);
                        fAssetUnitIDNumber = selectedItem.getKey();
                    }

                    @Override
                    public void onNothingSelected(AdapterView<?> parent) {
                        // 处理没有选中任何项的情况
                    }
                });
            }
        });


    }

    private void initPositionData() {

        Map<String, String> positionMap = KingDeeCommonUtil.getAssetPosition();
        // 创建适配器并绑定到 Spinner
        MapAdapter positionAdapter = new MapAdapter(this, positionMap);
        handler.post(new Runnable() {
            @Override
            public void run() {
                fAssetPosition.setAdapter(positionAdapter);
                fAssetPosition.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                    @Override
                    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                        Map.Entry<String, String> selectedItem = (Map.Entry<String, String>) parent.getItemAtPosition(position);
                        fAssetPositionNumber = selectedItem.getKey();
                    }

                    @Override
                    public void onNothingSelected(AdapterView<?> parent) {
                        // 处理没有选中任何项的情况
                    }
                });
            }
        });
    }

    private void initTypeData() {
        //类别
        Map<String, String> typeMap = KingDeeCommonUtil.getAssetType();
        MapAdapter typeAdapter = new MapAdapter(this, typeMap);
        handler.post(new Runnable() {
            @Override
            public void run() {
                fAssetType.setAdapter(typeAdapter);
                fAssetType.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                    @Override
                    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                        Map.Entry<String, String> selectedItem = (Map.Entry<String, String>) parent.getItemAtPosition(position);
                        fAssetTypeNumber = selectedItem.getKey();
                    }

                    @Override
                    public void onNothingSelected(AdapterView<?> parent) {
                        // 处理没有选中任何项的情况
                    }
                });
            }
        });
    }

    private void initDeptData() {
        //部门
        Map<String, String> useDeptMap = KingDeeCommonUtil.getUseDept();
        MapAdapter userDeptAdapter = new MapAdapter(this, useDeptMap);
        handler.post(new Runnable() {
            @Override
            public void run() {
                fAllocUseDept.setAdapter(userDeptAdapter);
                fAllocUseDept.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                    @Override
                    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                        Map.Entry<String, String> selectedItem = (Map.Entry<String, String>) parent.getItemAtPosition(position);
                        fAllocUseDeptNumber = selectedItem.getKey();
                    }

                    @Override
                    public void onNothingSelected(AdapterView<?> parent) {
                        // 处理没有选中任何项的情况
                    }
                });
            }
        });
    }

    private void initExpenseData() {
        //费用项目
        Map<String, String> expenseMap = KingDeeCommonUtil.getExpense();
        MapAdapter expenseAdapter = new MapAdapter(this, expenseMap);
        handler.post(new Runnable() {
            @Override
            public void run() {
                fAllocCostItem.setAdapter(expenseAdapter);
                fAllocCostItem.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                    @Override
                    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                        Map.Entry<String, String> selectedItem = (Map.Entry<String, String>) parent.getItemAtPosition(position);
                        fAllocCostItemNumber = selectedItem.getKey();
                    }

                    @Override
                    public void onNothingSelected(AdapterView<?> parent) {
                        // 处理没有选中任何项的情况
                    }
                });
            }
        });
    }

    private void initStatusData() {
        //资产状态
        Map<String, String> assetStatusMap = KingDeeCommonUtil.getAssetStatus();
        MapAdapter assetStatusAdapter = new MapAdapter(this, assetStatusMap);
        handler.post(new Runnable() {
            @Override
            public void run() {
                fAssetStatus.setAdapter(assetStatusAdapter);
                fAssetStatus.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                    @Override
                    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                        Map.Entry<String, String> selectedItem = (Map.Entry<String, String>) parent.getItemAtPosition(position);
                        fAssetStatusNumber = selectedItem.getKey();
                    }

                    @Override
                    public void onNothingSelected(AdapterView<?> parent) {
                        // 处理没有选中任何项的情况
                    }
                });
            }
        });
    }

    private void initPolicyData() {
        //会计政策
        Map<String, String> acctPolicyMap = KingDeeCommonUtil.getAcctPolicy();
        MapAdapter acctPolicyAdapter = new MapAdapter(this, acctPolicyMap);
        handler.post(new Runnable() {
            @Override
            public void run() {
                fAcctPolicy.setAdapter(acctPolicyAdapter);
                fAcctPolicy.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                    @Override
                    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                        Map.Entry<String, String> selectedItem = (Map.Entry<String, String>) parent.getItemAtPosition(position);
                        fAcctPolicyNumber = selectedItem.getKey();
                    }

                    @Override
                    public void onNothingSelected(AdapterView<?> parent) {
                        // 处理没有选中任何项的情况
                    }
                });
            }
        });
    }

    //初始化数据
    private void initData() {
        executorService.execute(() -> {
            initUnitData();
            initTypeData();
            initPositionData();
            initDeptData();
            initExpenseData();
            initStatusData();
            initPositionData();
            initPolicyData();

        });
    }


    // 模拟提交资产信息数据的函数
    private void submitAssetData(String assetNo, String assetName, String quantity, String unit,
                                 String position, String type, String policy, String orgCost,
                                 String fAcctDate, String useDept, String allocCostItem, String status) {
        executorService.execute(() -> {
            CommonUtil.openProgressDialog(AddAssetActivity.this, "加载中");
            String result = KingDeeUtil.submitAsset(assetNo, assetName, quantity, unit,
                    position, type, policy, orgCost,
                    fAcctDate, useDept, allocCostItem, status);
            CommonUtil.cancelProgressDialog(AddAssetActivity.this);
            if (StringUtils.isNotBlank(result)) {
                CommonUtil.openAlertDialog(AddAssetActivity.this, "提示", "提交成功", 0);
            } else {
                CommonUtil.openAlertDialog(AddAssetActivity.this, "提示", "提交失败", 0);
            }

            Log.i("TAG", "submitAssetData: " + result);
        });
    }


    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            finish();
        }
        return super.onOptionsItemSelected(item);
    }
}

